﻿using System;
using Core.Base.Module;
using Core.Extension;
using UnityEngine;

namespace Core.Mgr._Timer
{
    public static class TimerExtension
    {
        /// <summary>
        /// 启动计时器
        /// </summary>
        /// <param name="callBack">计时器事件</param>
        /// <param name="delay">调用延迟</param>
        /// <param name="doTimes">调用次数，-1表示无限循环</param>
        /// <param name="repeatInterval">调用间隔</param>
        /// <param name="bindObj">计时器所绑定的对象。不为空时，当对象销毁或Disable，都会销毁计时器</param>
        /// <returns>Timer Id</returns>
        public static int StartTimer(this MonoBehaviour bindObj, Action callBack, float delay = 0f, int doTimes = 1,
            float repeatInterval = 1f)
        {
            int curTimerId = TimerMgr.StartTimer(callBack, delay, doTimes, repeatInterval);

            //绑定自动销毁功能
            if (bindObj != null)
                bindObj.gameObject.OnDestroy(delegate { TimerMgr.EndTimer(curTimerId); });

            return curTimerId;
        }

        /// <summary>
        /// 启动计时器
        /// </summary>
        /// <param name="callBack">计时器事件</param>
        /// <param name="delay">调用延迟</param>
        /// <param name="doTimes">调用次数，-1表示无限循环</param>
        /// <param name="repeatInterval">调用间隔</param>
        /// <param name="bindModule">计时器所绑定的模块。不为空时，当模块卸载会自动结束计时器</param>
        public static int StartTimer(this BaseModule baseModule, Action callBack, float delay = 0f, int doTimes = 1,
            float repeatInterval = 1f, BaseModule bindModule = null)
        {
            if (bindModule == null)
            {
                bindModule = baseModule;
            } 

            int curTimerId = TimerMgr.StartTimer(callBack, delay, doTimes, repeatInterval);
            if (bindModule != null)
                bindModule.onUnload += delegate { TimerMgr.EndTimer(curTimerId); };

            return curTimerId;
        }
    }
}